package com.seadragon.app.ksr.json.gson;

import static com.seadragon.app.ksr.model.KsrConstants.gf;

import java.io.IOException;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Point;

public class PointAdapter extends TypeAdapter<Point> {
	@Override
	public Point read(JsonReader reader) throws IOException {
//		if (reader.peek() == JsonToken.NULL) {
//			reader.nextNull();
//			return null;
//		}
		double lat = 0d;
		double lon = 0d;
        JsonToken token = reader.peek();
        if (token.equals(JsonToken.BEGIN_OBJECT)) {
            reader.beginObject();
            while (!reader.peek().equals(JsonToken.END_OBJECT)) {
                if (reader.peek().equals(JsonToken.NAME)) {
                	String name = reader.nextName();
                    if (name.equals("lat"))
                    	lat = reader.nextDouble();
                    else if(name.equals("lon"))
                    	lon = reader.nextDouble();
                    else
                        reader.skipValue();
                }
            }
            reader.endObject();
        }
		return gf.createPoint(new Coordinate(lon, lat));
	}

	public void write(JsonWriter writer, Point value) throws IOException {
		if (value == null) {
			writer.nullValue();
			return;
		}
		String xy = "lat:"+value.getX() + ",lon:" + value.getY();
		writer.value(xy);
	}

}